// utils/auth.js
import Cookies from "js-cookie";
import axios from "axios";

const TOKEN_KEY = "h5_organization_token";
const DEFAULT_EXPIRES = 1; // 默认1天过期

/**
 * 设置Token
 * @param {string} token
 * @param {number} expires 过期天数（默认1天）
 */
export function setToken(token, expires = DEFAULT_EXPIRES) {
  Cookies.set(TOKEN_KEY, token, {
    expires,
    secure: import.meta.env.MODE === "production", // HTTPS only
    sameSite: "strict", // 防止CSRF
  });
}

/**
 * 获取Token
 * @returns {string|null}
 */
export function getToken() {
  return Cookies.get(TOKEN_KEY);
}

// 测试使用 获取临时token
export function setTempToken() {
  return new Promise((resolve, reject) => {
    //先登录获取token
    axios
      .post(`${import.meta.env.VITE_API_JAVA_ROOT}/relate/login`, {
        userName: "relate",
        password: "relate",
      })
      .then((response) => {
        const res = response.data || {};
        if (res.code === 200 && res.result) {
          const token = res.result.token || "";
          setToken(token);
          resolve(token);
        }
      });
  });
}

/**
 * 移除Token
 */
export function removeToken() {
  Cookies.remove(TOKEN_KEY);
}

/**
 * 检查是否已登录
 * @returns {boolean}
 */
export function isAuthenticated() {
  return !!getToken();
}
